package com.niiwoo.civet.user.service.local;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.dto.response.QueryLoanDeviceInfoResponseDTO;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.civet.user.dao.aggregation.UserCreditAgainsFakeInfo;
import com.niiwoo.civet.user.dao.aggregation.UserCreditBasicInfo;
import com.niiwoo.civet.user.dao.aggregation.UserCreditFlowInfo;
import com.niiwoo.civet.user.dao.entity.*;
import com.niiwoo.civet.user.dao.mapper.*;
import com.niiwoo.civet.user.dto.response.credit.*;
import com.niiwoo.civet.user.enums.*;
import com.niiwoo.civet.user.enums.UserEnum.RegisterDeviceType;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.tiancheng.enums.FunctionCodeEnum;
import com.niiwoo.tripod.tiancheng.request.afp.LoanAmountAgainsFakeRequest;
import com.niiwoo.tripod.tiancheng.request.afp.PublishLoanAgainsFakeRequest;
import com.niiwoo.tripod.tiancheng.request.common.RelationVerification;
import com.niiwoo.tripod.tiancheng.request.df.CreditDataFlowRequest;
import com.niiwoo.tripod.tiancheng.request.df.SpeedLoanCreditRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 天秤数据服务
 * @Author:LiJian
 * @Date:2017/11/14
 */
@Slf4j
@Service
public class TianchengDataService {

    @Autowired
    private PrivacyMasks privacyMasks;
    @Autowired
    private UserBasicInfoMapperExt userBasicInfoMapper;
    @Autowired
    private DataStatusMapperExt dataStatusMapper;
    @Autowired
    private UserLinkmanInfoMapperExt userLinkmanInfoMapper;
    @Autowired
    private UserProfessionInfoMapperExt professionInfoMapper;
    @Autowired
    private UserAuthorizationInfoMapperExt userAuthorizationInfoMapperExt;
    @Autowired
    private UserCreditCardAuthInfoMapperExt userCreditCardAuthInfoMapperExt;
    
    @Reference(version = "1.0.0")
    private ProjectDubboService projectDubboService;

    /**
     * 获取用户基本信息（天秤模型）
     * @param userId
     * @return
     */
    public BasicInfoDTO getBasicInfo(String userId) {
    	BasicInfoDTO tcBasicInfo = new BasicInfoDTO();
        tcBasicInfo.setUser_id(userId);
        UserCreditBasicInfo userCreditBasicInfo = userBasicInfoMapper.getUserCreditBasicInfo(userId);
        if (userCreditBasicInfo == null) throw new BizException("USR10028"); //用户不存在
        
        String mobileNo = userCreditBasicInfo.getMobileNo();
        // 手机号解密
        tcBasicInfo.setMobile_phone(StringUtils.isNoneBlank(mobileNo) ? privacyMasks.decryptPrivacy(mobileNo) : null);
        tcBasicInfo.setReal_name(userCreditBasicInfo.getRealName());
        String idCard = userCreditBasicInfo.getIdCard();
        // 身份证号解密
        tcBasicInfo.setIdentity_card(StringUtils.isNoneBlank(idCard) ? privacyMasks.decryptPrivacy(idCard) : null);
        tcBasicInfo.setNick_name(userCreditBasicInfo.getNickName());
        tcBasicInfo.setRegister_time(userCreditBasicInfo.getRegisterTime().getTime());

        // 天秤系统要求必须有设备类型，所以需要查询用户最后一次借款的设备信息
        QueryLoanDeviceInfoResponseDTO queryLoanDeviceInfoResponseDTO = projectDubboService.queryUserLastLoanDeviceInfo(userId);
        if (queryLoanDeviceInfoResponseDTO != null) {
            tcBasicInfo.setBlack_box(queryLoanDeviceInfoResponseDTO.getBlackBox());
        	if (queryLoanDeviceInfoResponseDTO.getOs() != null && !"".equals(queryLoanDeviceInfoResponseDTO.getOs())) {
        		if (queryLoanDeviceInfoResponseDTO.getOs().equalsIgnoreCase("Android")) { //Android
        			tcBasicInfo.setDevice_type(RegisterDeviceType.ANDROID.getValue().intValue());
        		} else if (queryLoanDeviceInfoResponseDTO.getOs().equalsIgnoreCase("iOS")) { //iOS
        			tcBasicInfo.setDevice_type(RegisterDeviceType.IOS.getValue().intValue());
        		} else {  // H5
        			tcBasicInfo.setDevice_type(RegisterDeviceType.WEB.getValue().intValue());
        		}
        	}
        } else {
        	tcBasicInfo.setDevice_type(userCreditBasicInfo.getDeviceType());
            tcBasicInfo.setBlack_box(userCreditBasicInfo.getBlackBox());
        }
        
        tcBasicInfo.setZhima_score(userCreditBasicInfo.getZhimaScore());
        tcBasicInfo.setShebao_city(userCreditBasicInfo.getShebaoCity());
        tcBasicInfo.setDegree(userCreditBasicInfo.getDegree());
        tcBasicInfo.setMarital_status(userCreditBasicInfo.getMaritalStatus());
        tcBasicInfo.setLiving_province(userCreditBasicInfo.getLivingProvince());
        tcBasicInfo.setLiving_city(userCreditBasicInfo.getLivingCity());
        tcBasicInfo.setLiving_area(userCreditBasicInfo.getLivingArea());
        tcBasicInfo.setLiving_address(userCreditBasicInfo.getLivingAddress());
        tcBasicInfo.setEmail(userCreditBasicInfo.getEmail());
        tcBasicInfo.setIp(userCreditBasicInfo.getIp());
        return tcBasicInfo;
    }

    /**
     * 获取工作信息（天秤模型）
     * @param userId
     * @return
     */
    public WorkInfoDTO getWorkInfo(String userId) {
    	WorkInfoDTO workInfo = null;
        UserProfessionInfo userProfessionInfo = professionInfoMapper.selectByPrimaryKey(userId);
        if(userProfessionInfo != null) {
            workInfo = new WorkInfoDTO();
            workInfo.setCompany_name(userProfessionInfo.getCompanyName());
            String companyPhone = userProfessionInfo.getCompanyPhone();
            workInfo.setPhone(StringUtils.isNotBlank(companyPhone) ? privacyMasks.decryptPrivacy(companyPhone) : "");
            workInfo.setCompany_province(userProfessionInfo.getCompanyProvince());
            workInfo.setCompany_city(userProfessionInfo.getCompanyCity());
            workInfo.setCompany_area(userProfessionInfo.getCompanyArea());
            workInfo.setCompany_address(userProfessionInfo.getCompanyAddress());
            workInfo.setCompany_department(userProfessionInfo.getDepartment());
        }

        return workInfo;
    }

    /**
     * 获取联系人信息（天秤模型）
     * @param userId
     * @return
     */
    public List<ContactPersonInfoDTO> getContactPersonInfoList(String userId) {
        List<ContactPersonInfoDTO> contactPersonInfoList = null;
        List<UserLinkmanInfo> userLinkmanInfoList = userLinkmanInfoMapper.selectByUserId(userId);
        if(CollectionUtils.isNotEmpty(userLinkmanInfoList)) {
            contactPersonInfoList = new ArrayList<>(userLinkmanInfoList.size());
            ContactPersonInfoDTO contactPersonInfo = null;
            for(UserLinkmanInfo userLinkmanInfo : userLinkmanInfoList) {
                contactPersonInfo = new ContactPersonInfoDTO();
                contactPersonInfo.setName(userLinkmanInfo.getName());
                contactPersonInfo.setPhone(privacyMasks.decryptPrivacy(userLinkmanInfo.getMobileNo()));
                LinkManRelationEnum linkManRelationEnum = LinkManRelationEnum.getByEventType(userLinkmanInfo.getRelation());
                contactPersonInfo.setRelation(linkManRelationEnum != null ? linkManRelationEnum.getDesc() : "");
                contactPersonInfoList.add(contactPersonInfo);
            }
        }

        return contactPersonInfoList;
    }

    /**
     * 天秤授信反欺诈中用户相关信息（AFP）
     * @param request
     * @return
     */
    public LoanAmountAgainsFakeRequest fillUserCreditAgainsFakeInfo(String userId, LoanAmountAgainsFakeRequest request) {
        UserCreditAgainsFakeInfo userCreditAgainsFakeInfo = userBasicInfoMapper.getUserCreditAgainsFakeInfo(userId);
        String mobileNo = userCreditAgainsFakeInfo.getMobileNo();
        request.setMobile_phone(StringUtils.isNoneBlank(mobileNo) ? privacyMasks.decryptPrivacy(mobileNo) : null);
        request.setAccount_login(StringUtils.isNoneBlank(mobileNo) ? privacyMasks.decryptPrivacy(mobileNo) : null);
        String idCard = userCreditAgainsFakeInfo.getIdCard();
        request.setIdentity_card(StringUtils.isNoneBlank(idCard) ? privacyMasks.decryptPrivacy(idCard) : null);
        request.setName(userCreditAgainsFakeInfo.getRealName());
        List<RelationVerification> relationVerifications = this.getRelationVerification(userId);
        if(CollectionUtils.isNotEmpty(relationVerifications)) {
            for(RelationVerification verification : relationVerifications) {
                verification.setRelation_phone(privacyMasks.decryptPrivacy(verification.getRelation_phone()));
            }
            request.setRELATION_VERIFICATION(relationVerifications);
        }
        request.setDegree(this.getDegree(userCreditAgainsFakeInfo.getEducationLevel()));
        String blackBox = userCreditAgainsFakeInfo.getBlackBox();
        request.setBlackBox(StringUtils.isNotBlank(blackBox) ? blackBox : "");
        return request;
    }


    /**
     * 天秤借款反欺诈中用户相关信息（AFP）
     * @param request
     * @return
     */
    public PublishLoanAgainsFakeRequest fillUserPublishLoanAgainsFakeInfo(String userId, PublishLoanAgainsFakeRequest request) {

        UserCreditAgainsFakeInfo userCreditAgainsFakeInfo = userBasicInfoMapper.getUserCreditAgainsFakeInfo(userId);
        String mobileNo = userCreditAgainsFakeInfo.getMobileNo();
        request.setMobile_phone(StringUtils.isNoneBlank(mobileNo) ? privacyMasks.decryptPrivacy(mobileNo) : null);
        request.setAccount_login(StringUtils.isNoneBlank(mobileNo) ? privacyMasks.decryptPrivacy(mobileNo) : null);
        String idCard = userCreditAgainsFakeInfo.getIdCard();
        request.setIdentity_card(StringUtils.isNoneBlank(idCard) ? privacyMasks.decryptPrivacy(idCard) : null);
        request.setName(userCreditAgainsFakeInfo.getRealName());
        request.setRELATION_VERIFICATION(this.getRelationVerification(userId));
        request.setDegree(this.getDegree(userCreditAgainsFakeInfo.getEducationLevel()));
        if(userCreditAgainsFakeInfo.getLivingProvince() != null) {
            StringBuilder livingSb = new StringBuilder();
            livingSb.append(userCreditAgainsFakeInfo.getLivingProvince());
            livingSb.append(userCreditAgainsFakeInfo.getLivingCity());
            livingSb.append(userCreditAgainsFakeInfo.getLivingArea());
            livingSb.append(userCreditAgainsFakeInfo.getLivingAddress());
            request.setUserLivingPlace(livingSb.toString());
        }
        return request;
    }

    /**
     * 天秤借款授信回流用户相关信息
     * @param userId
     * @param creditDataFlowRequest
     * @param platform 平台类型
     * @return
     */
    public CreditDataFlowRequest fillSpeedLoanCreditRequest(String userId, CreditDataFlowRequest creditDataFlowRequest, int platform, Integer socialSecurityExpire) {
        UserCreditFlowInfo userCreditFlowInfo = userBasicInfoMapper.getUserCreditFlowInfo(userId);
        String userIdStr = String.valueOf(userId);
        creditDataFlowRequest.setUserId(userIdStr);
        // 用户基本信息
        CreditDataFlowRequest.UserBasicInfo userBasicInfo = new CreditDataFlowRequest.UserBasicInfo();
        userBasicInfo.setUserStatus((byte) 1);
        userBasicInfo.setUserType("1");
        String mobileNo = userCreditFlowInfo.getMobileNo();
        userBasicInfo.setTelNo(StringUtils.isNoneBlank(mobileNo) ? privacyMasks.decryptPrivacy(mobileNo) : null);
        userBasicInfo.setDegreeType(userCreditFlowInfo.getEducationLevel() != null ? userCreditFlowInfo.getEducationLevel().intValue() : null);
        Byte maritalStatus = this.marriageTypeTransform(userCreditFlowInfo.getMaritalStatus());
        userBasicInfo.setMaritalStatus(maritalStatus != null ? maritalStatus.intValue() : null);
        userBasicInfo.setLivingProvince(userCreditFlowInfo.getLivingProvince());
        userBasicInfo.setLivingCity(userCreditFlowInfo.getLivingCity());
        userBasicInfo.setLivingArea(userCreditFlowInfo.getLivingArea());
        userBasicInfo.setLivingAddress(userCreditFlowInfo.getLivingAddress());
        userBasicInfo.setRealName(userCreditFlowInfo.getRealName());
        userBasicInfo.setCardType(1);
        userBasicInfo.setCardAddress(userCreditFlowInfo.getCardAddress());
        String idCard = userCreditFlowInfo.getIdCard();
        userBasicInfo.setIdentityCard(StringUtils.isNoneBlank(idCard) ? privacyMasks.decryptPrivacy(idCard) : null);
        Date cardValidity = userCreditFlowInfo.getCardValidity();
        if(cardValidity != null) {
            userBasicInfo.setCardValidity(FastDateFormat.getInstance("yyyy-MM-dd").format(cardValidity));
        }
        userBasicInfo.setSocialSecurityDateVerifyState(this.socialSecurityAuthStatus(userId, platform, socialSecurityExpire) ? 1 : 0);
        userBasicInfo.setSesameMark(userCreditFlowInfo.getZhimaScore());
        userBasicInfo.setUpdateTime(userCreditFlowInfo.getBaseUpdateTime().getTime() * 1000);
        userBasicInfo.setIsValidateIdentity(0);
        DataStatus dataStatus = dataStatusMapper.selectByUserIdAndType(userId, UserDataTypeEnum.TWO_ELEMENT.getValue());
        if(dataStatus != null && UserDataStatusEnum.RealNameAuthStatus.PASS_CERTIFIED.getStatus().byteValue() == dataStatus.getDataStatus()) {
            userBasicInfo.setIsValidateIdentity(1);
            userBasicInfo.setValidateIdentityTime(dataStatus.getAuthTime()==null?null:(dataStatus.getAuthTime().getTime() * 1000));
        }
        creditDataFlowRequest.setUserBasicInfo(userBasicInfo);

        // 工作信息
        CreditDataFlowRequest.WorkInfo workInfo = new CreditDataFlowRequest.WorkInfo();
        workInfo.setCompanyName(userCreditFlowInfo.getCompanyName());
        workInfo.setPosition(userCreditFlowInfo.getPosition());
        workInfo.setDeparment(userCreditFlowInfo.getDepartment());
        workInfo.setCompanyProvince(userCreditFlowInfo.getCompanyProvince());
        workInfo.setCompanyCity(userCreditFlowInfo.getCompanyCity());
        workInfo.setCompanyArea(userCreditFlowInfo.getCompanyArea());
        workInfo.setCompanyAddress(userCreditFlowInfo.getCompanyAddress());
        workInfo.setCompanyPhone(StringUtils.isNotBlank(userCreditFlowInfo.getCompanyPhone()) ? privacyMasks.decryptPrivacy(userCreditFlowInfo.getCompanyPhone()) : "");
        creditDataFlowRequest.setWorkInfo(workInfo);

        // 家庭信息
        List<UserLinkmanInfo> userLinkmanInfoList = userLinkmanInfoMapper.selectByUserId(userId);
        List<CreditDataFlowRequest.FamilyInfo> familyInfoList = new ArrayList<>(userLinkmanInfoList.size());
        CreditDataFlowRequest.FamilyInfo familyInfo = null;
        for(UserLinkmanInfo userLinkmanInfo : userLinkmanInfoList) {
            familyInfo = new CreditDataFlowRequest.FamilyInfo();
            familyInfo.setContactName(userLinkmanInfo.getName());
            LinkManRelationEnum linkManRelationEnum = LinkManRelationEnum.getByEventType(userLinkmanInfo.getRelation());
            if(linkManRelationEnum != null) {
                familyInfo.setRelation(linkManRelationEnum.getDesc());
            }
            familyInfo.setContactMobilePhone(privacyMasks.decryptPrivacy(userLinkmanInfo.getMobileNo()));
            familyInfoList.add(familyInfo);
        }
        creditDataFlowRequest.setFamilyInfo(familyInfoList);


        return creditDataFlowRequest;
    }

    public String getDegree(Byte educationLevel) {
        if(educationLevel != null) {
            UserPersonalEnum.UserEduLevelEnum userEduLevelEnum = UserPersonalEnum.UserEduLevelEnum.getByLevel(educationLevel.byteValue());
            switch (userEduLevelEnum) {
                case SPECIAL_SCHOOL:
                    return null;
                case JUNIOR_COLLEGE:
                    return "8";
                case UNDERGRADUATE:
                    return "5";
                case MASTER:
                    return "2";
                case DOCTOR:
                    return "1";
                default:
                    return null;
            }
        }
        return null;
    }

    private Byte marriageTypeTransform(Byte maritalStatus) {
        if(maritalStatus == null) {
            return null;
        }
        UserPersonalEnum.UserMaritalStatusEnum maritalStatusEnum = UserPersonalEnum.UserMaritalStatusEnum.getByLevel(maritalStatus);
        switch (maritalStatusEnum) {
            case MARRIED:
                return 1;
            case UNMARRIED:
                return 0;
            case DIVORCE:
                return 2;
            default:
                return null;
        }
    }

    public List<RelationVerification> getRelationVerification(String userId) {
        List<UserLinkmanInfo> userLinkmanInfoList = userLinkmanInfoMapper.selectByUserId(userId);
        List<RelationVerification> relationVerificationList = new ArrayList<>();
        RelationVerification relationVerification = null;
        for(UserLinkmanInfo userLinkmanInfo : userLinkmanInfoList) {
            relationVerification = new RelationVerification();
            relationVerification.setRelation_name(userLinkmanInfo.getName());
            relationVerification.setRelation_phone(userLinkmanInfo.getMobileNo());
            relationVerificationList.add(relationVerification);
        }
        return relationVerificationList;
    }

    private List<SpeedLoanCreditRequest.VecRelaTion> getVecRelaTion(String userId) {
        List<UserLinkmanInfo> userLinkmanInfoList = userLinkmanInfoMapper.selectByUserId(userId);
        List<SpeedLoanCreditRequest.VecRelaTion> vecRelaTionList = new ArrayList<>();
        SpeedLoanCreditRequest.VecRelaTion vecRelaTion = null;
        for(UserLinkmanInfo userLinkmanInfo : userLinkmanInfoList) {
            vecRelaTion = new SpeedLoanCreditRequest.VecRelaTion();
            vecRelaTion.setContactName(userLinkmanInfo.getName());
            vecRelaTion.setContactMobilePhone(userLinkmanInfo.getMobileNo());
            LinkManRelationEnum linkManRelationEnum = LinkManRelationEnum.getByEventType(userLinkmanInfo.getRelation());
            if(linkManRelationEnum != null) {
                vecRelaTion.setContactRelation(linkManRelationEnum.getDesc());
            }
            vecRelaTionList.add(vecRelaTion);
        }
        return vecRelaTionList;
    }

    public boolean socialSecurityAuthStatus(String userId, int platform, Integer socialSecurityExpire) {
        DataStatus socialSecurityStatus = null;
        if(PlatformTypeEnum.NIIWOO.getType() == platform) {
            socialSecurityStatus = dataStatusMapper.selectByUserIdAndType(userId, UserDataTypeEnum.SOCIAL_SECURITY_OPERATOR_AUTHORIZE.getValue());
        }else if(PlatformTypeEnum.RONG360.getType() == platform) {
            socialSecurityStatus = dataStatusMapper.selectByUserIdAndType(userId, UserDataTypeEnum.R360_SOCIAL_SECURITY_OPERATOR_AUTHORIZE.getValue());
        }
        if(socialSecurityStatus == null) {
            return false;
        }
        // 判断社保过期时间
        if(UserDataStatusEnum.SocialSecurityStatus.ALREADY_CREDIT.getStatus().equals(socialSecurityStatus.getDataStatus()) ||
                UserDataStatusEnum.SocialSecurityStatus.GETSUCCESS.getStatus().equals(socialSecurityStatus.getDataStatus())) {
            DateTime authTime = new DateTime(socialSecurityStatus.getAuthTime());
            if(socialSecurityExpire != null && authTime.plusDays(socialSecurityExpire).isBeforeNow()) {
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 查询用户天秤额度评分卡所需参数
     * @param userId
     * @param headFunctionCode
     * @return
     */
    public CreditScoreCardDTO queryCreditScoreCardParam(String userId, String headFunctionCode) {
        log.info("查询用户天秤额度评分卡所需参数 userId={} headFunctionCode={}", userId, headFunctionCode);
        CreditScoreCardDTO creditScoreCardDTO = new CreditScoreCardDTO();
        try {
            //社保贷参数、信用卡贷（第一部分参数）
			if (FunctionCodeEnum.LIBRA_SOCIAL_SECURITY_LOAN.getHeadFunctionCode().equalsIgnoreCase(headFunctionCode)
					|| FunctionCodeEnum.LIBRA_CREDIT_CARD_LOAN_TWO.getHeadFunctionCode().equalsIgnoreCase(headFunctionCode)
					|| FunctionCodeEnum.LIBRA_CONSUME_LOAN.getHeadFunctionCode().equalsIgnoreCase(headFunctionCode)) {
                List<Byte> dataTypes = Arrays.asList(UserDataTypeEnum.JD_AUTHORIZE.getValue(), UserDataTypeEnum.EDUCATION_AUTHORIZE.getValue());
                List<DataStatus> dataStatusList = dataStatusMapper.getStatusListByUserid(userId, dataTypes);
                if(!dataStatusList.isEmpty()){
                    for (DataStatus dataStatus : dataStatusList) {
                        //设置京东授权状态
                        if (dataStatus.getDataType().equals(UserDataTypeEnum.JD_AUTHORIZE.getValue())){
                            //已授权或者获取授权数据才为已授权，除此之外都为未授权
                            if (UserDataStatusEnum.JdStatus.GETSUCCESS.getStatus().equals(dataStatus.getDataStatus()) ||
                                    UserDataStatusEnum.JdStatus.ALREADY_CREDIT.getStatus().equals(dataStatus.getDataStatus())){
                                creditScoreCardDTO.setJd_auth(UserDataStatusEnum.JdStatus.ALREADY_CREDIT.getStatus());
                            } else {
                                creditScoreCardDTO.setJd_auth(UserDataStatusEnum.JdStatus.NOCREDIT.getStatus());
                            }
                            //京东登陆账号
                            UserAuthorizationInfo userAuthorizationInfo = userAuthorizationInfoMapperExt.selectById(userId);
                            creditScoreCardDTO.setJd_login_name(userAuthorizationInfo.getJdLoginName());
                        }
                        //设置学历授信状态
                        if (dataStatus.getDataType().equals(UserDataTypeEnum.EDUCATION_AUTHORIZE.getValue())){
                            //已授权或者获取授权数据才为已授权，除此之外都为未授权
                            if (UserDataStatusEnum.EducationStatus.GETSUCCESS.getStatus().equals(dataStatus.getDataStatus()) ||
                                    UserDataStatusEnum.EducationStatus.ALREADY_CREDIT.getStatus().equals(dataStatus.getDataStatus())){
                                creditScoreCardDTO.setXx_auth(UserDataStatusEnum.EducationStatus.ALREADY_CREDIT.getStatus());
                            } else {
                                creditScoreCardDTO.setXx_auth(UserDataStatusEnum.EducationStatus.NOCREDIT.getStatus());
                            }

                        }
                        // 驭信授信状态
                        if (dataStatus.getDataType().equals(UserDataTypeEnum.CREDIT_CARD_AUTHORIZE.getValue())){
                            //已授权或者获取授权数据才为已授权，除此之外都为未授权
                            if (UserDataStatusEnum.CreditCardStatus.GETSUCCESS.getStatus().equals(dataStatus.getDataStatus()) ||
                                    UserDataStatusEnum.CreditCardStatus.ALREADY_CREDIT.getStatus().equals(dataStatus.getDataStatus())){
                                creditScoreCardDTO.setYx_auth(UserDataStatusEnum.CreditCardStatus.ALREADY_CREDIT.getStatus());

                                //驭信相关参数
                                UserCreditCardAuthInfo userCreditCardAuthInfo = userCreditCardAuthInfoMapperExt.selectByPrimaryKey(userId);
                                creditScoreCardDTO.setYx_entry_id(userCreditCardAuthInfo.getEntryId());
                                creditScoreCardDTO.setYx_login_name(userCreditCardAuthInfo.getLoginName());
                            } else {
                                creditScoreCardDTO.setYx_auth(UserDataStatusEnum.CreditCardStatus.NOCREDIT.getStatus());
                            }
                        }
                        // 是否授权社保
                        if (dataStatus.getDataType().equals(UserDataTypeEnum.SOCIAL_SECURITY_OPERATOR_AUTHORIZE.getValue())){
                            //已授权或者获取授权数据才为已授权，除此之外都为未授权
                            if (UserDataStatusEnum.SocialSecurityStatus.GETSUCCESS.getStatus().equals(dataStatus.getDataStatus()) ||
                                    UserDataStatusEnum.SocialSecurityStatus.ALREADY_CREDIT.getStatus().equals(dataStatus.getDataStatus())){
                                creditScoreCardDTO.setInsurance_auth(UserDataStatusEnum.SocialSecurityStatus.ALREADY_CREDIT.getStatus());
                            } else {
                                creditScoreCardDTO.setInsurance_auth(UserDataStatusEnum.SocialSecurityStatus.NOCREDIT.getStatus());
                            }
                        }
                    }
                }
            }

            //信用卡贷（第二部分参数）
            if (FunctionCodeEnum.LIBRA_CREDIT_CARD_LOAN_TWO.getHeadFunctionCode().equalsIgnoreCase(headFunctionCode)){
                //驭信相关参数
                UserCreditCardAuthInfo userCreditCardAuthInfo = userCreditCardAuthInfoMapperExt.selectByPrimaryKey(userId);
                creditScoreCardDTO.setYx_entry_id(userCreditCardAuthInfo.getEntryId());
                creditScoreCardDTO.setYx_login_name(userCreditCardAuthInfo.getLoginName());
            }
        } catch (Exception e) {
            log.error("查询用户天秤额度评分卡所需参数 userId={} headFunctionCode={}", userId, headFunctionCode, e);
        }
        return creditScoreCardDTO;
    }

    public SocialSecurityTeCreditScoreCardDTO queryCreditScoreCardParamForSocialSecurityTe(String userId) {
        log.info("查询用户天秤额度评分卡所需参数 userId={} headFunctionCode={}", userId);
        SocialSecurityTeCreditScoreCardDTO socialSecurityTeCreditScoreCardDTO = new SocialSecurityTeCreditScoreCardDTO();

        List<DataStatus> dataStatusList = dataStatusMapper.getStatusListByUserid(
                userId,
                Arrays.asList(
                        UserDataTypeEnum.CREDIT_CARD_AUTHORIZE.getValue(),
                        UserDataTypeEnum.EDUCATION_AUTHORIZE.getValue(),
                        UserDataTypeEnum.JD_AUTHORIZE.getValue()
                )
        );

        if(CollectionUtils.isEmpty(dataStatusList)){
            return socialSecurityTeCreditScoreCardDTO;
        }

        //信用卡
        DataStatus yxDataStatus = getDataStatus(UserDataTypeEnum.CREDIT_CARD_AUTHORIZE, dataStatusList);
        Byte yxDataStatusValue = yxDataStatus.getDataStatus();
        if(UserDataStatusEnum.CreditCardStatus.ALREADY_CREDIT.getStatus().equals(yxDataStatusValue)
                || UserDataStatusEnum.CreditCardStatus.GETSUCCESS.getStatus().equals(yxDataStatusValue)) {
            socialSecurityTeCreditScoreCardDTO.setYxAuthTime(yxDataStatus.getAuthTime());
            UserCreditCardAuthInfo userCreditCardAuthInfo = userCreditCardAuthInfoMapperExt.selectByPrimaryKey(userId);
            if(userCreditCardAuthInfo!=null) {
                socialSecurityTeCreditScoreCardDTO.setYx_entry_id(userCreditCardAuthInfo.getEntryId());
                socialSecurityTeCreditScoreCardDTO.setYx_login_name(userCreditCardAuthInfo.getLoginName());
            }
        }

        //学历
        DataStatus xxDataStatus = getDataStatus(UserDataTypeEnum.EDUCATION_AUTHORIZE, dataStatusList);
        Byte xxDataStatusValue = xxDataStatus.getDataStatus();
        if(UserDataStatusEnum.EducationStatus.ALREADY_CREDIT.getStatus().equals(xxDataStatusValue)
                || UserDataStatusEnum.EducationStatus.GETSUCCESS.getStatus().equals(xxDataStatusValue)) {
            socialSecurityTeCreditScoreCardDTO.setXxAuthTime(xxDataStatus.getAuthTime());
        }

        //京东
        DataStatus jdDataStatus = getDataStatus(UserDataTypeEnum.JD_AUTHORIZE, dataStatusList);
        Byte jdDataStatusValue = jdDataStatus.getDataStatus();
        if(UserDataStatusEnum.JdStatus.ALREADY_CREDIT.getStatus().equals(jdDataStatusValue)
                || UserDataStatusEnum.JdStatus.GETSUCCESS.getStatus().equals(jdDataStatusValue)) {
            socialSecurityTeCreditScoreCardDTO.setJdAuthTime(jdDataStatus.getAuthTime());
            UserAuthorizationInfo userAuthorizationInfo = userAuthorizationInfoMapperExt.selectById(userId);
            if(userAuthorizationInfo!=null) {
                socialSecurityTeCreditScoreCardDTO.setJd_login_name(userAuthorizationInfo.getJdLoginName());
            }
        }


        return socialSecurityTeCreditScoreCardDTO;
    }

    public CreditCardTeCreditScoreCardDTO queryCreditScoreCardParamForCreditCardTe(String userId) {
        log.info("查询用户天秤额度评分卡所需参数 userId={} headFunctionCode={}", userId);
        CreditCardTeCreditScoreCardDTO creditCardTeCreditScoreCardDTO = new CreditCardTeCreditScoreCardDTO();

        List<DataStatus> dataStatusList = dataStatusMapper.getStatusListByUserid(
                userId,
                Arrays.asList(
                        UserDataTypeEnum.SOCIAL_SECURITY_OPERATOR_AUTHORIZE.getValue(),
                        UserDataTypeEnum.EDUCATION_AUTHORIZE.getValue(),
                        UserDataTypeEnum.JD_AUTHORIZE.getValue()
                )
        );

        if(CollectionUtils.isEmpty(dataStatusList)){
            return creditCardTeCreditScoreCardDTO;
        }

        //社保
        DataStatus shebaoDataStatus = getDataStatus(UserDataTypeEnum.SOCIAL_SECURITY_OPERATOR_AUTHORIZE, dataStatusList);
        creditCardTeCreditScoreCardDTO.setInsuranceAuthTime(shebaoDataStatus.getAuthTime());

        //学历
        DataStatus xxDataStatus = getDataStatus(UserDataTypeEnum.EDUCATION_AUTHORIZE, dataStatusList);
        creditCardTeCreditScoreCardDTO.setXxAuthTime(xxDataStatus.getAuthTime());

        //京东
        DataStatus jdDataStatus = getDataStatus(UserDataTypeEnum.JD_AUTHORIZE, dataStatusList);
        creditCardTeCreditScoreCardDTO.setJdAuthTime(jdDataStatus.getAuthTime());
        UserAuthorizationInfo userAuthorizationInfo = userAuthorizationInfoMapperExt.selectById(userId);
        creditCardTeCreditScoreCardDTO.setJd_login_name(userAuthorizationInfo.getJdLoginName());


        return creditCardTeCreditScoreCardDTO;
    }

    private DataStatus getDataStatus(UserDataTypeEnum userDataTypeEnum, List<DataStatus> dataStatusList){
        DataStatus dataStatus = new DataStatus();
        if(CollectionUtils.isEmpty(dataStatusList)){
            return dataStatus;
        }
        for(DataStatus d : dataStatusList){
            if(userDataTypeEnum.getValue().equals(d.getDataType())){
                return d;
            }
        }
        return dataStatus;
    }
}
